package com.example.mybatis.session.impl;

import com.example.mybatis.config.Config;
import com.example.mybatis.executor.Executor;
import com.example.mybatis.mapper.MapperMethod;
import com.example.mybatis.mapper.MapperProxy;
import com.example.mybatis.sqlsession.SqlSession;

import java.lang.reflect.Proxy;

public class DefaultSqlSession  implements SqlSession {

    private final Config config;
    private final Executor executor;

    public DefaultSqlSession(Config config, Executor executor) {
        this.config = config;
        this.executor = executor;
    }

    @Override
    public Config getConfig() {
        return this.config;
    }


    @Override
    public <T> T selectOne(MapperMethod mapperMethod, Object[] args) {
        return executor.query(config,mapperMethod,args);
    }

    @Override
    public int insert(MapperMethod mapperMethod, Object[] args) {
        return executor.update(config,mapperMethod,args);
    }

    @Override
    public int update(MapperMethod mapperMethod, Object[] args) {
        return executor.update(config,mapperMethod,args);
    }

    @Override
    public int delete(MapperMethod mapperMethod, Object[] args) {
        return executor.update(config,mapperMethod,args);
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        MapperProxy mapperProxy = new MapperProxy(type,this);
        return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{type},mapperProxy);

       // return null;
    }
}
